package com.itlong.cloud.controller.sdkV1.cloud.entrance.server;

import com.itlong.cloud.POJO.DTO.property.IotCloudEntranceStateDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKGetByDeviceUniqueDTO;
import com.itlong.cloud.POJO.DTO.sdk.CloudElevatorSDKServerGetElevatorPageDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.sdk.CloudEntranceSDKEntranceInfoVO;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.IotOpenDoorSourceEnum;
import com.itlong.cloud.enumerate.PropertyEquipTypeEnum;
import com.itlong.cloud.enumerate.ecode.AppErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.SDKErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.sdk.ICloudEntranceSDKServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <desc>
 *      云门禁SDK服务端云端对旺龙云端控制器
 * </desc>
 *
 * @createDate 2019/03/14
 */
@RestController
@RequestMapping("/cloud/entrance")
public class CloudEntranceSDKServerCloudController extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(CloudEntranceSDKServerCloudController.class);

    @Autowired
    private ICloudEntranceSDKServiceClient iCloudEntranceSDKServiceClient;

    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    private RedisService redisService;

    /**
     * <desc>
     * 查询唯一标识
     * <desc/>
     *
     * @return Object   标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/03/14
     */
    @ResponseBody
    @PostMapping("/getEntranceKey")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ENTRANCE_DEVICE_UNIQUE_LOG_DESC)
    public Object getEntranceKey() {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKServerGetElevatorPageDTO.class, request);
            String projectId = cloudElevatorSDKServerGetElevatorPageDTO.getProjectId();
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "查询项目下门禁设备唯一码列表");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ENTRANCE_TYPE_LOG_DESC);

            List<String> deviceArr = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
            List<Map<String, String>> allList = new ArrayList<>();
            deviceArr.forEach(str -> {
                Map<String, String> map = new HashMap<>();
                map.put("deviceUnique", str);
                allList.add(map);
            });
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),allList);
        } catch (Exception e) {
            throw new DataAccessException("【云门禁SDK_服务端_查询项目下门禁设备唯一码列表】查询项目下门禁设备唯一码列表失败",e);
        }
    }

    /**
     * <desc>
     *      根据设备唯一码查询门禁信息
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Qiang.S
     * @createDate 2019/03/14
     */
    @ResponseBody
    @PostMapping("/getEntranceInfo")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ENTRANCE_INFO_LOG_DESC)
    public Object getEntranceInfo(){
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKGetByDeviceUniqueDTO.class, request);
            String projectId = cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId();

            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "根据设备唯一码" + cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique() + "查询门禁信息");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ENTRANCE_TYPE_LOG_DESC);
            if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
            cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
            cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId());
            List<String> deviceUniques = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }
            List<String> deviceUniqueParams = StringHandlerUtil.splitStringList(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique());
            for (String deviceUniqueParam : deviceUniqueParams) {
                if (!deviceUniques.contains(deviceUniqueParam)) {
                    return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
                }
            }
            List<CloudEntranceSDKEntranceInfoVO> cloudElevatorSDKGetByDeviceUniqueVOS = iCloudEntranceSDKServiceClient.getEntranceInfo(cloudElevatorSDKGetByDeviceUniqueDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),cloudElevatorSDKGetByDeviceUniqueVOS);
        } catch (Exception e) {
            throw new DataAccessException("【云门禁SDK_服务端_根据设备唯一码查询门禁信息】根据设备唯一码查询门禁信息失败",e);
        }
    }

    /**
     * <desc>
     *      iot开门
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/03/14
     */
    @ResponseBody
    @RequestMapping("/netOpenDoor")
    @LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_OPEN_ENTRANCE_LOG_DESC)
    public Object netOpenDoor() throws Exception{
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKGetByDeviceUniqueDTO.class, request);
            String projectId = cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId();
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "根据设备唯一码" + cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique() + "开门");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ENTRANCE_TYPE_LOG_DESC);

            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
            cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
            cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId());
            List<String> deviceUniques = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }
            if (!deviceUniques.contains(cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique())) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl()) || (!"1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl()) &&
                    !"0".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl()))) {
                cloudElevatorSDKGetByDeviceUniqueDTO.setOpenCtrl("1");
            }
            if ("1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl())) {//开门时
                if (StringUtils.isBlank(cloudElevatorSDKGetByDeviceUniqueDTO.getRobotId())) {//非机器人开门
                    cloudElevatorSDKGetByDeviceUniqueDTO.setTimeout(1);
                }else {
                    if (cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() == null ||
                            cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() < 0 || cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout() > 300) {
                        return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_TIME_OUT_ERR.getErrorCode());
                    }
                }
            }else {
                cloudElevatorSDKGetByDeviceUniqueDTO.setTimeout(1);
            }
            String deviceUnique = cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique();
            //查询门禁设备的iot账号及绑定的iot产品key
            Map<String,Object> entrance = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKey(deviceUnique);
            //获取门禁设备型号
            Integer entranceType = iAppDeviceServiceClient.getEntranceTypeInfo(deviceUnique);
            CorrelationData correlationId = new CorrelationData(UUID.randomUUID().toString());
            if(entrance != null && entrance.get("deviceUnique") != null) {
                if (PropertyEquipTypeEnum.CLOUD_WIPPEN_DEVICE.getType() == entranceType)//联动器
                {
                    //增加了robotGo联动器呼梯输入楼层名称的判断字符串 fooltype robotGo项目默认传1:楼层名称;其他的傳null不影響其他的功能
                    if (cloudElevatorSDKGetByDeviceUniqueDTO.getFoolType()!=null && cloudElevatorSDKGetByDeviceUniqueDTO.getFoolType()=="1"){
                        iCloudEntranceServiceClient.wippenOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                                Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(),
                                cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl(), cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout().toString(), entrance.get("productKey").toString(),
                                cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(), IotOpenDoorSourceEnum.ITLONG_SDK.getType().toString(),
                                cloudElevatorSDKGetByDeviceUniqueDTO.getDoorDirection(),cloudElevatorSDKGetByDeviceUniqueDTO.getFloor(),correlationId.getId(),cloudElevatorSDKGetByDeviceUniqueDTO.getRobotFlag(),"1");

                    }else {
                        iCloudEntranceServiceClient.wippenOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                                Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(),
                                cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl(), cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout().toString(), entrance.get("productKey").toString(),
                                cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(), IotOpenDoorSourceEnum.ITLONG_SDK.getType().toString(),
                                cloudElevatorSDKGetByDeviceUniqueDTO.getDoorDirection(),cloudElevatorSDKGetByDeviceUniqueDTO.getFloor(),correlationId.getId(),cloudElevatorSDKGetByDeviceUniqueDTO.getRobotFlag(),null);

                    }
                }else {
                    iCloudEntranceServiceClient.entranceOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                            Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl(), cloudElevatorSDKGetByDeviceUniqueDTO.getTimeout().toString(), entrance.get("productKey").toString(),
                            cloudElevatorSDKGetByDeviceUniqueDTO.getAppId(), "",cloudElevatorSDKGetByDeviceUniqueDTO.getRobotFlag());
                }
            }else{
                return new MessageVO(AppErrorCodeEnum.CLOUD_ENTRANCE_EXISTS.getErrorCode());
            }
            boolean isOpen = false;
            if ("1".equals(cloudElevatorSDKGetByDeviceUniqueDTO.getOpenCtrl())) {//开门时
                //判断门禁当前状态是否是开门，如果是开门则返回成功，否则返回失败
                int count = 0;
                while(count<10){
                    Thread.sleep(500);
                    IotCloudEntranceStateDTO dto = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ENTRANCE_STATE_CACHE +
                            cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique()), IotCloudEntranceStateDTO.class);
                    if(dto != null && dto.getMsgCode() == 0){
                        isOpen = true;
                        break;
                    }
                    count++;
                }
            }else {
                isOpen = true;
            }
            Map<String,Object> result = new HashMap<>();
            result.put("isOpen",isOpen+"");
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),result);
        }catch (Exception e){
            throw new DataAccessException("【APP_首页版块】远程开门失败",e);
        }
    }

    /**
     * <desc>
     *      查询云门禁状态
     * </desc>
     *
     * @return
     * @author Qiang.S
     * @createDate 2019/04/03
     */
    @ResponseBody
    @RequestMapping("/getEntranceStatus")
    //@LoggerInfo(operateDesc = LogDescConstant.SDK_SERVER_GET_ENTRANCE_LOG_DESC)
    public Object getEntranceStatus() throws Exception{
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            CloudElevatorSDKGetByDeviceUniqueDTO cloudElevatorSDKGetByDeviceUniqueDTO = HttpProtocolUtil.parseRequestParamToDTO(CloudElevatorSDKGetByDeviceUniqueDTO.class, request);
            String projectId = cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId();
            //保存生成操作日志所需信息 详细描述和接口类别
            request.setAttribute("remark",projectId + "根据设备唯一码" + cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique() + "查询门禁状态");
            request.setAttribute("portType",LogDescConstant.SDK_CLOUD_ENTRANCE_TYPE_LOG_DESC);

            CloudElevatorSDKServerGetElevatorPageDTO cloudElevatorSDKServerGetElevatorPageDTO = new CloudElevatorSDKServerGetElevatorPageDTO();
            cloudElevatorSDKServerGetElevatorPageDTO.setAppId(cloudElevatorSDKGetByDeviceUniqueDTO.getAppId());
            cloudElevatorSDKServerGetElevatorPageDTO.setProjectId(cloudElevatorSDKGetByDeviceUniqueDTO.getProjectId());
            cloudElevatorSDKServerGetElevatorPageDTO.setRoleId(cloudElevatorSDKGetByDeviceUniqueDTO.getRoleId());
            List<String> deviceUniques = iCloudEntranceSDKServiceClient.getEntranceKey(cloudElevatorSDKServerGetElevatorPageDTO);
            if (deviceUniques == null || deviceUniques.isEmpty()) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }
            String deviceUnique = cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique();
            if (!deviceUniques.contains(deviceUnique)) {
                return new MessageVO(SDKErrorCodeEnum.SDK_SERVER_NO_DEVICE_UNIQUE_ERR.getErrorCode());
            }
            IotCloudEntranceStateDTO entranceStatus = null;
            List<IotCloudEntranceStateDTO> list = new ArrayList<>();
            //查询门禁设备的iot账号及绑定的iot产品key
            Map<String, Object> entrance = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKey(deviceUnique);
            int count = 0;
            int flag = 0;//上报指令标记
            while (count < 10) {
                entranceStatus = JsonUtil.toObject(redisService.getKeysForDevice(RedisConstant.REDIS_IOT_CLOUD_ENTRANCE_STATE_CACHE +
                        cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique()), IotCloudEntranceStateDTO.class);
//
//                        (IotCloudEntranceStateDTO) redisService.decodeObject(RedisConstant.REDIS_IOT_CLOUD_ENTRANCE_STATE_CACHE +
//                        cloudElevatorSDKGetByDeviceUniqueDTO.getDeviceUnique(), new TypeReference<IotCloudEntranceStateDTO>() {
//                });
                if (entranceStatus != null) {
                    list.add(entranceStatus);
                    break;
                } else {
                    if (flag == 0) {//保证只发送一次
                        //如从缓存中读取不到电梯的信息触发iot发送电梯控制指令
                        iCloudEntranceServiceClient.entranceStatusCtrl("itlong", entrance.get("deviceUnique").toString(),
                                Integer.valueOf(deviceUnique.substring(deviceUnique.length() - 4, deviceUnique.length())).toString(), "300",
                                entrance.get("productKey").toString());
                        flag++;
                    }
                }
                count++;
                Thread.sleep(500);
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),list);
        }catch (Exception e){
            throw new DataAccessException("【APP_首页版块】远程开门失败",e);
        }
    }

}
